<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import {
  getAuthPage,
  updateAuth,
  deleteAuth,
  downloadTemplateAppApi,
  exportAuth,
  getBrandList,
} from "@/api/auth";
import { getDeptOptions } from "@/api/dept";
import { getRoleOptions } from "@/api/role";

import { AuthForm, AuthQuery, AuthPageVO } from "@/api/auth/types";

import type { UploadInstance } from "element-plus";
import { genFileId } from "element-plus";

const queryFormRef = ref(ElForm); // 查询表单
const authFormRef = ref(ElForm); // 用户表单
const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<AuthQuery>({
  pageNum: 1,
  pageSize: 10,
  type: 0,
});
const dateTimeRange = ref("");
const total = ref(0); // 数据总数
const zIndex = ref(1);
const imgIdex = ref(0);
const pageData = ref<AuthPageVO[]>(); // 用户分页数据
const deptList = ref<OptionType[]>(); // 部门下拉数据源
const roleList = ref<OptionType[]>(); // 角色下拉数据源

const listData = ref([""]);

const brandList = ref([] as any);

const modelList = ref([]);

const showViewer = ref(false);

const showViewerTwo = ref(false);

watch(dateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startTime = newVal[0];
    queryParams.endTime = newVal[1];
  } else {
    queryParams.startTime = "";
    queryParams.endTime = "";
  }
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});

// 用户表单数据
const formData = reactive<AuthForm>({
  authenticationId: 0,
  status: "0",
  userId: 0,
  remark: "",
  frontImg: "",
  backImg: "",
  drivingImg: "",
  authPrice: 0,
});

// 用户导入数据
const importData = reactive({
  deptId: undefined,
  file: undefined,
  fileList: [],
});

// 校验规则
const rules = reactive({
  status: [{ required: true, message: "请选择认证状态", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getAuthPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function getImg(index: any) {
  showViewer.value = true;
  imgIdex.value = index;
}

function closeViewer() {
  showViewer.value = false;
}

function closeViewerTwo() {
  showViewerTwo.value = false;
}
/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  dateTimeRange.value = "";
  queryParams.pageNum = 1;
  queryParams.startTime = undefined;
  queryParams.endTime = undefined;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.authenticationId);
}

/** 加载角色下拉数据源 */
async function loadRoleOptions() {
  getRoleOptions().then((response) => {
    roleList.value = response.data;
  });
}

/** 加载部门下拉数据源 */
async function loadDeptOptions() {
  getDeptOptions().then((response) => {
    deptList.value = response.data;
  });
}

async function openDialog(type: string, row?: any) {
  dialog.visible = true;
  dialog.type = type;
  // 用户表单弹窗
  await loadDeptOptions();
  await loadRoleOptions();
  if (row != undefined && row.authenticationId) {
    dialog.title = "认证审核";

    Object.assign(formData, { ...row });
    listData.value = [];
    if (formData.frontImg != undefined) {
      listData.value.push(formData.frontImg);
    }

    if (formData.backImg != undefined) {
      listData.value.push(formData.backImg);
    }

    if (formData.drivingImg != undefined) {
      listData.value.push(formData.drivingImg);
    }
  }
}

function GetDropdownListItems() {
  getBrandList()
    .then(({ data }) => {
      brandList.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleSelect(val: any) {
  console.log(val);
  formData.brandName = val.brandName;
  modelList.value = val.children;
}
function handleSelectModel(val: any) {
  formData.model = val.brandName;
}

function blurForBug() {
  formData.brandName = "";
}

function createFilter(queryString: any) {
  return (res: any) => {
    if (formData.brandName == queryString) {
      return true;
    } else {
      return (
        res.brandName.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      );
    }
  };
}
// 客户 modelList
function FilterEntityName(queryString: any, cb: any) {
  var EntityNameList2 = brandList.value;
  var results = queryString
    ? EntityNameList2.filter(createFilter(queryString))
    : EntityNameList2;
  // 调用 callback 返回建议列表的数据
  cb(results);
}

function filterModel(queryString: any, cb: any) {
  var modelNameList2 = modelList.value;
  var results = queryString
    ? modelNameList2.filter(createFilter(queryString))
    : modelNameList2;
  // 调用 callback 返回建议列表的数据
  cb(results);
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    authFormRef.value.resetFields();
    authFormRef.value.clearValidate();

    formData.authenticationId = undefined;
    formData.status = "1";
  } else if (dialog.type === "user-import") {
    importData.file = undefined;
    importData.fileList = [];
  }
}

/** 删除用户 */
function handleDelete(id?: number) {
  const authenticationIds = [id || removeIds.value].join(",");
  if (!authenticationIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除认证?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteAuth(authenticationIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

function getImgCur(imgUrl: any) {
  listData.value = [];
  listData.value.push(imgUrl);
  showViewerTwo.value = true;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  if (formData.status == "0") {
    ElMessage.warning("请选择认证状态");
    return false;
  }

  authFormRef.value.validate((valid: any) => {
    if (valid) {
      const authenticationId = formData.authenticationId;
      loading.value = true;

      updateAuth(formData)
        .then(() => {
          ElMessage.success("认证成功");
          closeDialog();
          resetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);
/** Excel文件 Change */
function handleFileChange(file: any) {
  importData.file = file.raw;
}

/** Excel文件 Exceed  */
function handleFileExceed(files: any) {
  uploadRef.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
  importData.file = file;
}

/** 导出用户 */
function handleExport() {
  exportAuth(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

/** 下载导入模板 */
function downloadTemplate() {
  downloadTemplateAppApi().then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

function handleSuccess(response: any, file: any, fileList: any) {
  ElMessage.success(response.data);
}

onMounted(() => {
  handleQuery();
  GetDropdownListItems();
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 部门树
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <dept-tree v-model="queryParams.deptId" @node-click="handleQuery" />
      </el-col> -->

      <!-- 用户列表 -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="用户名/昵称/手机号"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="创建时间">
              <el-date-picker
                class="!w-[240px]"
                v-model="dateTimeRange"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />删除</el-button
                >
              </div>

              <div>
                <el-dropdown split-button>
                  导入
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="downloadTemplate">
                        <i-ep-download />下载模板</el-dropdown-item
                      >
                      <el-dropdown-item>
                        <i-ep-top />
                        <el-upload
                          ref="uploadRef"
                          style="height: 30px"
                          action="/dev-api/api/car/auth/impAuth"
                          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                          :limit="1"
                          :auto-upload="true"
                          :file-list="importData.fileList"
                          :on-change="handleFileChange"
                          :on-exceed="handleFileExceed"
                          :on-success="handleSuccess"
                        >
                          <div style="margin-top: 5px">导入数据</div>
                        </el-upload>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button class="ml-3" @click="handleExport"
                  ><template #icon><i-ep-download /></template>导出</el-button
                >
              </div>
            </div>
          </template>
          <el-image-viewer
            v-if="showViewerTwo"
            :z-index="10000"
            @close="closeViewerTwo"
            :url-list="listData"
          />
          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              align="center"
              label="序号"
              type="index"
              width="150"
            />
            <el-table-column
              key="username"
              label="用户名"
              align="center"
              prop="loginName"
            />
            <el-table-column
              label="用户昵称"
              width="120"
              align="center"
              prop="nickName"
            />
            <el-table-column
              label="头像"
              align="center"
              prop="headImg"
              width="120"
            >
              <template #default="scope">
                <span
                  ><img
                    :src="scope.row.headImg"
                    style="height: 60px"
                    @click="getImgCur(scope.row.headImg)"
                /></span>
              </template>
            </el-table-column>
            <el-table-column
              label="认证车辆品牌"
              align="center"
              prop="brandName"
              width="200"
            />
            <el-table-column
              label="认证车辆型号"
              align="center"
              prop="model"
              width="200"
            />
            <el-table-column
              label="认证申请时间"
              align="center"
              prop="createDate"
              width="200"
            />

            <el-table-column label="车辆正面照" align="center" width="120">
              <template #default="scope">
                <span
                  ><img
                    :src="scope.row.frontImg"
                    style="height: 60px"
                    @click="getImgCur(scope.row.frontImg)"
                /></span>
              </template>
            </el-table-column>
            <el-table-column label="背面照" align="center" width="120">
              <template #default="scope">
                <span
                  ><img
                    :src="scope.row.backImg"
                    style="height: 60px"
                    @click="getImgCur(scope.row.backImg)"
                /></span>
              </template>
            </el-table-column>
            <el-table-column label="行驶证" align="center" width="120">
              <template #default="scope">
                <span
                  ><img
                    :src="scope.row.drivingImg"
                    style="height: 60px"
                    @click="getImgCur(scope.row.drivingImg)"
                /></span>
              </template>
            </el-table-column>

            <el-table-column
              label="状态"
              align="center"
              prop="status"
              width="120"
            >
              <template #default="scope">
                <span v-if="scope.row.status == 0"> 待认证 </span>
                <span v-if="scope.row.status == 1"> 已认证 </span>

                <span v-if="scope.row.status == 2"> 认证驳回 </span>
                <span v-if="scope.row.status == 3">已撤销</span>
              </template>
            </el-table-column>

            <el-table-column
              label="备注"
              align="center"
              prop="remark"
              width="200"
            />

            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status == 0"
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('user-form', scope.row)"
                  ><i-ep-edit />认证审核</el-button
                >

                <el-button
                  v-if="scope.row.status == 1 || scope.row.status == 2"
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('user-form', scope.row)"
                  ><i-ep-edit />认证审核</el-button
                >

                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('user-form', scope.row)"
                  >查看</el-button
                >
              </template>
            </el-table-column>

            <!-- <el-table-column label="操作" fixed="right" width="220">
              <template #default="scope">
                <el-button
                  v-hasPerm="['sys:user:reset_pwd']"
                  type="primary"
                  size="small"
                  link
                  @click="resetPassword(scope.row)"
                  ><i-ep-refresh-left />重置密码</el-button
                >
                <el-button
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('user-form', scope.row.id)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="primary"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column> -->
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <el-form
        v-if="dialog.type === 'user-form'"
        ref="authFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="申请账号" prop="username">
          <el-input
            v-model="formData.loginName"
            :readonly="!!formData.authenticationId"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="formData.nickName" placeholder="请输入用户昵称" />
        </el-form-item>

        <el-form-item label="申请时间" prop="email">
          <el-input
            v-model="formData.createDate"
            placeholder="请输入申请时间"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="车辆品牌" prop="email">
          <el-autocomplete
            clearable
            class="handle-input-width"
            v-model="formData.brandName"
            value-key="brandName"
            :fetch-suggestions="FilterEntityName"
            :trigger-on-focus="true"
            placeholder="请输入车辆品牌"
            @clear="blurForBug()"
            @select="handleSelect"
            style="width: 100%"
          >
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="车辆型号" prop="model">
          <el-autocomplete
            clearable
            class="handle-input-width"
            v-model="formData.model"
            value-key="brandName"
            :fetch-suggestions="filterModel"
            :trigger-on-focus="true"
            placeholder="请输入车辆型号"
            @clear="blurForBug()"
            @select="handleSelectModel"
            style="width: 100%"
          >
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="上传图片" prop="email">
          <el-image-viewer
            v-if="showViewer"
            @close="closeViewer"
            :initial-index="imgIdex"
            :url-list="listData"
            :zIndex="zIndex"
          />

          <div style="width: 33%; float: left">
            <el-image
              :src="formData.frontImg"
              style="height: 200px"
              @click="getImg(0)"
            ></el-image>
          </div>
          <div style="width: 33%; float: left; padding: 10px">
            <el-image
              :src="formData.backImg"
              style="height: 200px"
              @click="getImg(1)"
            ></el-image>
          </div>
          <div style="width: 33%; float: left">
            <el-image
              :src="formData.drivingImg"
              style="height: 200px"
              @click="getImg(2)"
            ></el-image>
          </div>
        </el-form-item>

        <el-form-item label="备注信息" prop="mobile">
          <el-input
            v-model="formData.remark"
            placeholder="请输入备注信息"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1" value="1">通过</el-radio>
            <el-radio :label="2" value="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">通 过</el-button>
          <el-button @click="dialog.visible = false">返 回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
